<template>
	<view class="container">
		<view class="login-header">
			<image class="logo" src="https://pengtou-1322587508.cos.ap-shanghai.myqcloud.com/static/images/new_logo.png" mode="heightFix"></image>
			<view class="slogan">PENG一下，趣收获</view>
		</view>
		<view class="login-mid">
			<image class="login-bg" src="https://pengtou-1322587508.cos.ap-shanghai.myqcloud.com/static/images/user/login-bg.png" mode="heightFix">
			</image>
			<button class="btn-primary login-btn" @tap.stop.prevent="chatLogin" :open-type="mobileState == 0 ? 'getPhoneNumber' : ' '"
				@getphonenumber="getPhoneNumber">一键授权登录</button>
			<view class="login-no" @click="noLogin">暂不登录</view>
		</view>
		<view class="login-foot">
			<view class="pdCkeckOut" @tap.stop="onAgreement">
				<mycheckbox :check="agreement"></mycheckbox>
			</view>
			<view class="textBox">
				<text @tap="onAgreement">我已同意</text>
				<text class="agreement"
					@click="checkAgreement('https://pengtou-1322587508.cos.ap-shanghai.myqcloud.com/static/pdf/register.pdf', '用户协议')">用户协议</text>
				<text>与</text>
				<text class="agreement"
					@click="checkAgreement('https://pengtou-1322587508.cos.ap-shanghai.myqcloud.com/static/pdf/privacy.pdf', '隐私协议')">隐私协议</text>
			</view>
		</view>
		<uv-toast ref="toast"></uv-toast>
	</view>
</template>

<script>
	import mp from "@/mixins/mp.js";
	import {
		mapState
	} from "vuex";
	const app = getApp();

	export default {
		mixins: [mp],
		components: {},
		data() {
			return {
				agreement: false,
				mobileState: 0,
				user_info: {},
				couponDetail: {},
				userSig: '',
			};
		},
		/**
		 * 计算属性
		 */
		computed: {
			...mapState({
				isLogin: state => state.isLogin,
				isSDKReady: state => state.isSDKReady
			})
		},
		onLoad(options) {},
		onShow: function() {
			this.$store.commit('reset')
			this.$nextTick(() => {
				if (app.globalData.systemInfo.uniPlatform != 'web') {
					this.loginHanle()
				}
			})
		},
		/**
		 * 下拉
		 */
		onPullDownRefresh: function() {},
		/**
		 * 触底
		 */
		onReachBottom() {},
		/**
		 * 滚动
		 */
		onPageScroll(e) {},
		methods: {
			onAgreement(value) {
				this.agreement = !this.agreement;
			},
			noLogin() {
				// uni.navigateBack()
				uni.reLaunch({
					url: '/pages/index/index'
				});
			},
			loginHanle() {
				let that = this;
				that.$refs.toast.show({
					type: 'loading',
				})
				app.globalData.isLogin = false
				// 获取临时登录凭证code。
				uni.login({
					provider: 'weixin',
					success(result) {
						app._post_form("/client/noToken/login", {
								code: result.code,
								grantType: 'wechat_client',
								userInfo: {
									"avatar": "",
									"city": "",
									"country": "",
									"mobile": "",
									"nickName": "",
									"province": "",
									"sex": "",
									"userId": 0
								}
							},
							(res) => {
								if (res.code == 0 || res.code == 200) {
									that.mobileState = res.data.mobileState
									that.userSig = res.data.userSig
									that.$store.commit("onChstUserSig", res.data.userSig);
									app.globalData.token = res.data.authInfo.token
									uni.setStorageSync('token', res.data.authInfo.token);
									uni.setStorageSync("expiresIn", new Date(res.data.authInfo.expiration))
									uni.setStorageSync("expire", res.data.authInfo.expire)
									that.user_info = res.data
									that.$refs.toast.hide()
								}
							}, false, () => {
								that.$refs.toast.hide()
							})
					}
				})
			},
			checkAgreement(url, name) {
				let that = this;
				that.$refs.toast.show({
					type: 'loading',
				})
				wx.downloadFile({
					url: url, //文件地址
					success(res) {
						wx.saveFile({ //重点 wx.saveFile一定要有   避免文件存储找不到  然后打开失败
							tempFilePath: res.tempFilePath,
							filePath: wx.env.USER_DATA_PATH + '/' + name + '.pdf',
							success(res) {
								wx.openDocument({
									filePath: res.savedFilePath,
									fileType: "pdf",
									showMenu: true,
									success: function(res) {
										that.$refs.toast.hide()
									},
									fail: function(res) {
										that.$refs.toast.hide()
									},
								})
							}
						})
					},
				})
			},
			getPhoneNumber(e) {
				let that = this;
				app.globalData.bind_Phone = true
				let invite_code = uni.getStorageSync('invite_code') ? uni.getStorageSync('invite_code') : null;
				app._post_form("/client/wechat/bindPhone", {
						code: e.detail.code,
						shareUserId: invite_code
					},
					(res) => {
						if (res.code == 0 || res.code == 200) {
							that.mobileState = 1;
							that.chatLogin()
						}
					})
			},
			getPhoneNumberAg() {
				uni.showToast({
					title: '勾选用户协议与隐私协议',
					icon: 'none',
					duration: 2000
				});
			},
			getCoupon() {
				return new Promise((resolve, reject) => {
					app._get(
						"/client/coupon/query/coupon-toast", null,
						(result) => {
							let res = result.data
							resolve(res);
						}, null, () => {
							resolve(false);
						}
					);
				});
			},

			async getCouponDetail() {
				const result = await this.getCoupon()
				return new Promise((resolve, reject) => {
					app._post_form(
						"/client/coupon/query/coupon-detail", result.couponId,
						(result) => {
							this.couponDetail = result.data
							resolve(result);
						}, null, () => {
							resolve(false);
						}
					);
				});
			},
			chatLogin() {
				if (!this.agreement) {
					this.getPhoneNumberAg();
					return
				}
				if (this.mobileState == 0) {
					return
				}


				let that = this;
				console.log(that.user_info);
				that.$refs.toast.show({
					type: 'loading',
				})
				// let promise = uni.$TUIKit.login({
				// 	userID: that.user_info.authInfo.userId,
				// 	userSig: that.userSig
				// });
				// this.getCouponDetail(),
				// Promise.all([promise]).then((res) => {
				// 	let user_info = that.user_info
				// 	uni.setStorageSync('user_info', user_info);
				// 	uni.setStorageSync('coupon_detail', that.couponDetail);
				// 	app.globalData.couponDetail = that.couponDetail
				// 	app.globalData.UserInfo = user_info
				// 	app.globalData.isLogin = !!user_info
				// 	app.globalData.bind_Phone = that.mobileState == 1

				// 	//登录成功后 更新登录状态
				// 	this.$store.commit("toggleIsLogin", true);
				// 	//tim 返回的用户信息
				// 	uni.setStorageSync('userTIMInfo', JSON.stringify(res.data))
				// 	that.golastPage();
				// 	that.$refs.toast.hide()
				// }).catch((err) => {
				// 	that.$refs.toast.hide()
				// 	console.warn('login error:', err); // 登录失败的相关信息
				// });


				let user_info = that.user_info
				uni.setStorageSync('user_info', user_info);
				uni.setStorageSync('coupon_detail', that.couponDetail);
				app.globalData.couponDetail = that.couponDetail
				app.globalData.UserInfo = user_info
				app.globalData.isLogin = !!user_info
				app.globalData.bind_Phone = that.mobileState == 1

				//登录成功后 更新登录状态
				this.$store.commit("toggleIsLogin", true);
				//tim 返回的用户信息
				// uni.setStorageSync('userTIMInfo', JSON.stringify(res.data))
				that.golastPage();
				that.$refs.toast.hide()
			},

			//-----------没用
			getChstUserSig() {
				return new Promise((resolve, reject) => {
					app._post_form(
						"/client/im/create-user-sig", null,
						(result) => {
							this.userSig = result.data.userSig
							resolve();
						}, null, () => {
							resolve();
						}
					);
				});
			},
			lastLogin() {


			},
			// 跳转到上一页或首页
			golastPage() {
				let localLastPage = uni.getStorageSync('goCurrentPage');
				if (localLastPage == 'pages/index/index') {
					uni.removeStorageSync('goCurrentPage');
					app.navigationBack();
				} else {
					uni.reLaunch({
						url: '/pages/index/index'
					});
				}
				app._post_form("/client/getById", null, (res) => {
					this.$store.commit("changeBindWx", !!res.data.wechatNumber);
				}, false, () => {})
				// return
				// 判断本地是否存有页面路径，有则跳转
				// let localLastPage = uni.getStorageSync('goCurrentPage');
				// if (localLastPage) {
				// 	uni.removeStorageSync('goCurrentPage');
				// 	app.navigationTo(localLastPage)
				// 	return;
				// }
				// let lastPage = app.lastPage()
				// //判断上一页是否是登录页面，否则直接跳转
				// if (lastPage) {
				// 	app.navigationBack();
				// } else {
				// 	uni.reLaunch({
				// 		url: '/pages/index/index'
				// 	});
				// }
			},
			onNavigateBack() {
				app.navigationBack();
			}
		},
	}
</script>
<style lang="scss" scoped>
	.container {
		min-height: 100vh;
		background: linear-gradient(180deg, #F6FEE7, #FFFFFF);
		display: flex;
		flex-direction: column;
		align-items: center;

		.login-header {
			display: flex;
			flex-direction: column;
			align-items: center;
			margin-top: 210rpx;

			.logo {
				height: 100rpx;
				margin-bottom: 24rpx;
			}

			.slogan {
				font-size: 22rpx;
				font-weight: 400;
				color: #999B9B;
				line-height: 44rpx;
				margin-bottom: 192rpx;
			}
		}

		.login-mid {
			display: flex;
			flex-direction: column;
			align-items: center;
			margin-bottom: 210rpx;
			width: 100%;
			position: relative;

			.login-bg {
				height: 316rpx;
				margin-bottom: 76rpx;
			}

			.login-btn {
				width: calc(100% - 77rpx * 2);
				// margin-top: calc(-88rpx - 54rpx);
				margin-bottom: 54rpx;
			}

			.login-btn-mobileState {
				position: relative;
				// margin-top: calc(-88rpx - 54rpx);
				z-index: 2;
			}

			.login-btn-agreement {
				position: relative;
				margin-top: calc(-88rpx - 54rpx);
				z-index: 3;
			}

			.login-no {
				font-size: 32rpx;
				font-weight: 900;
				color: #999B9B;
				line-height: 45rpx;
			}
		}

		.login-foot {
			font-size: 22rpx;
			font-weight: 400;
			color: #999B9B;
			line-height: 44rpx;
			display: flex;
			align-items: center;

			.pdCkeckOut {
				padding: 15rpx;
				padding-right: 10rpx;
			}

			// .textBox {
			// 	margin-left: 10rpx;
			// }
			.agreement {
				color: #004098;
				margin: 0 6rpx;
			}
		}
	}
</style>